<template>
    <el-dialog
      destroy-on-close
      draggable
      title="Merge"
      width="400"
      v-model="visible"
    >
        <el-form :model="formParam" ref="custForm" :rules="rules">
          <el-form-item label="merge blNo" label-width="120px" prop="id" required>
            <el-select v-model="formParam.id" filterable clearable>
              <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in idOptions"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visible = false">{{ $t("ship.button.cancel") }}</el-button>
            <el-button type="primary" :loading="isLoading" @click="onSubmit">{{ $t("ship.button.submit") }}</el-button>
          </span>
        </template>
      </el-dialog>
</template>
<script setup lang="ts" name="MergeModal">
import {  ElMessageBox } from "element-plus"; 
import { ref, reactive, defineExpose, getCurrentInstance } from 'vue';
import service from "@/utils/request";

const proxy = getCurrentInstance()?.proxy
const visible = ref(false);
const isLoading = ref(false)

const rules = ref({
  id: [{ required: true, message: "B/L NO. can't be blank" }]
});

const formParam = reactive({
  id: null,
  details: []
})

const onInit = ({ details }) => {
  visible.value = true;
  formParam.id = null;
  formParam.details = details; 
}

const idOptions = computed(() => {
  return formParam.details.map(item => {
    return {
      label: item.blNo,
      value: item.id
    }
  })
})

const onSubmit = () => {
  ElMessageBox.confirm("Confirm to combine the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    proxy.$refs["custForm"].validate(valid => {
      if (valid) {
        isLoading.value = true;
        service.post("/shipping/cargoManifest/combine", formParam).then(() => {
          proxy.$emit("success");
          visible.value = false;
        }).finally(() => {
          isLoading.value = false;
        })
      }
    })
})
}

defineExpose({ onInit });
</script>
